//
//  NetWorkTool.swift
//  Weibo
//
//  Created by gdarkness on 16/3/25.
//  Copyright © 2016年 gdarkness. All rights reserved.
//

import UIKit

import AFNetworking

class NetWorkTool: NSObject {
        //单例
        static let shareInstance :NetWorkTool = NetWorkTool()
        
        let afnManager :AFHTTPSessionManager = AFHTTPSessionManager(baseURL:baseURL)
        
        //私有化构造函数
        private override init(){
            super.init()
            //设置afn支持 text/plain类型
            afnManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
    }
    
    //如果在控制器或VM，直接调用AFN的方法，如果AFN以后不用了。想换其他的框架或者AFN升级，请求参数更换，到时候更换非常麻烦
    func requestGET(URLString: String, parameters: AnyObject, requestCallBack:(requst: [String: AnyObject]?, error:NSError?) -> ()) {
        afnManager.GET(URLString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            //网络请求回来的都是JSON格式
            let dict = result as? [String: AnyObject]
            requestCallBack(requst: dict, error: nil)
            }) { (_, error) -> Void in
                requestCallBack(requst: nil, error: error)
        }
    }
    
    //封装POST请求
    func requsetPOST(urlString: String,parameters: AnyObject,requestCallBack: (request: [String: AnyObject]?,error: NSError? )-> ()) {
        afnManager.POST(urlString, parameters: parameters, progress: nil, success: { (_, result) -> Void in
            let dict = result as? [String: AnyObject]
            requestCallBack(request: dict, error: nil)
            }) { (_, error) -> Void in
                requestCallBack(request: nil, error: error)
        }
    }
    
}
